package com.dz.order.service;

import com.dz.common.base.ResponseBase;
import com.dz.order.domain.entity.OrderItem;
import com.dz.order.feign.GoodsFeignService;
import com.dz.order.feign.entity.Sku;
import com.dz.order.feign.entity.Spu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @ClassName : CartServiceImpl
 * @Description :
 * @Author : ming
 * @Date: 2021-03-08 14:33
 **/
@Service
public class CartServiceImpl implements CartService{
    @Autowired
    private GoodsFeignService goodsFeignService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void add(Integer num, Long id, String username) throws Exception {
        ResponseBase<Sku> skuResult = goodsFeignService.getSkuById(id);
        if (skuResult!=null||skuResult.getRtnCode()==200){
            Sku sku= skuResult.getData();
            ResponseBase<Spu> spuResult = goodsFeignService.getSpuById(sku.getSpuId());
            Spu spu= spuResult.getData();
            OrderItem orderItem= skuOrderItem(sku,spu,num);
            redisTemplate.boundHashOps("Cart_"+username).put(id,orderItem);
        }
    }

    private OrderItem skuOrderItem(Sku sku, Spu spu, Integer num) {
        OrderItem orderItem = new OrderItem();
        orderItem.setSpuId(sku.getSpuId());
        orderItem.setSkuId(sku.getId());
        orderItem.setName(sku.getName());
        orderItem.setPrice(sku.getPrice());
        orderItem.setNum(num);
        orderItem.setMoney(num*orderItem.getPrice());       //单价*数量
        orderItem.setPayMoney(num*orderItem.getPrice());    //实付金额
        orderItem.setImage(sku.getImage());
        orderItem.setWeight(sku.getWeight()*num);           //重量=单个重量*数量

        //分类ID设置
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        return orderItem;
    }
}
